package com.ruoyi.app.common

import cn.hutool.core.util.RandomUtil
import com.alibaba.fastjson.JSONObject
import com.aliyun.imageenhan20190930.models.ImageBlindCharacterWatermarkRequest
import com.aliyun.imageenhan20190930.models.ImageBlindPicWatermarkRequest
import com.aliyun.teaopenapi.models.Config
import com.aliyun.vod20170321.Client
import com.aliyun.vod20170321.models.AddWatermarkRequest
import com.aliyun.vod20170321.models.AddWatermarkResponse
import com.ruoyi.util.log
import com.ruoyi.util.upload


const val ACCESS_KEY: String = "LTAI5tRQ1acQfyPAnkCWvMAd"
const val ACCESS_SECRET: String = "SVVk0Non9jDhpSdISorUnfYZFBqs9c"

fun aigc(id: Long, userId: Long) =
    """
        aigc:{"company":"合肥研律网络科技有限公司","AIFlag":"AIGC","version":"1.0","timespan":"${System.currentTimeMillis()}","contentDataid":"$id","userid":"$userId"}
    """.trimIndent()


/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
@Throws(java.lang.Exception::class)
fun createClient(): Client {
    val config = Config() // 必填，您的 AccessKey ID
        .setAccessKeyId(ACCESS_KEY) // 必填，您的 AccessKey Secret
        .setAccessKeySecret(ACCESS_SECRET)
    // Endpoint 请参考 https://api.aliyun.com/product/vod
    config.endpoint = "vod.cn-shanghai.aliyuncs.com"
    return Client(config)
}

/**
 * 添加水印配置信息函数
 */
@Throws(Exception::class)
fun addWatermark(fileUrl: String): AddWatermarkResponse {

    val client = createClient()
    return client.addWatermark(AddWatermarkRequest().apply {
        name = "addwatermark"
        setFileUrl(fileUrl.upload())
        setWatermarkConfig(buildImageWatermarkConfig().toJSONString())
        setType("Image")
    })
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
@Throws(java.lang.Exception::class)
fun createImageClient(): com.aliyun.imageenhan20190930.Client {
    val config = Config() // 必填，您的 AccessKey ID
        .setAccessKeyId(ACCESS_KEY) // 必填，您的 AccessKey Secret
        .setAccessKeySecret(ACCESS_SECRET)
    // Endpoint 请参考 https://api.aliyun.com/product/imageenhan
    config.endpoint = "imageenhan.cn-shanghai.aliyuncs.com"
    return com.aliyun.imageenhan20190930.Client(config)
}

fun addPicWaterMark(logo: String, pic: String): String =
    createImageClient().imageBlindPicWatermark(ImageBlindPicWatermarkRequest().apply {
        functionType = "encode_pic_plus"
        logoURL = logo.upload()
        qualityFactor = 100
        outputFileType = "png"
        originImageURL = pic.upload()
    }).body.data.getWatermarkImageURL()

fun String.decode(): String {
    return createImageClient().imageBlindCharacterWatermark(ImageBlindCharacterWatermarkRequest().apply {
        functionType = "decode_text_plus"
        watermarkImageURL = this@decode
        qualityFactor = 100
        outputFileType = "jpg"
    }).body.data.getTextImageURL()
}

fun addTextWaterMark(textLogo: String, pic: String): String =
    createImageClient().imageBlindCharacterWatermark(ImageBlindCharacterWatermarkRequest().apply {
        functionType = "encode_text_plus"
        text = textLogo
        qualityFactor = 100
        originImageURL = pic.upload()
        outputFileType = "jpg"
    }).body.also { log.info("requestId: ${it.requestId}") }.data.getWatermarkImageURL()
fun main() {
//    addPicWaterMark("https://shuiyin-program.oss-cn-hangzhou.aliyuncs.com//userfiles/32994181.png",
//        "https://shuiyin-program.oss-cn-hangzhou.aliyuncs.com//userfiles/20230331100209.jpg")

//    println(
//        aigc(1234, 14435)
//    )

//    println(
//        addTextWaterMark(
//            "安徽崝澎网络科技有限公司:${RandomUtil.randomNumbers(6)}",
//            "https://yanlv-video.oss-cn-shanghai.aliyuncs.com//929012.jpg"
//        )
//    )
    println("http://vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com/eas-img-watermark/24-04-29-17/_encode_text_plus_286548789636039158.jpg?Expires=1714384735&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRpDvh1&Signature=jBEZ3pN2D9A1vOBNEEH4ktfcsK8%3D".decode())
    //println(add("https://shuiyin-program.oss-cn-hangzhou.aliyuncs.com//userfiles/20230327171756.jpg"))
}

/**
 * 构建图片水印的配置数据，根据具体设置需求修改对应的参数值
 * @return
 */
fun buildImageWatermarkConfig(): JSONObject {
    val watermarkConfig = JSONObject()
    //水印的横向偏移距离
    watermarkConfig["Dx"] = "10"
    //水印的纵向偏移距离
    watermarkConfig["Dy"] = "10"
    //水印显示的宽
    watermarkConfig["Width"] = "66"
    //水印显示的高
    watermarkConfig["Height"] = "66"
    //水印显示的相对位置(左上、右上、左下、右下)
    watermarkConfig["ReferPos"] = "BottomLeft"
    //水印显示的时间线(开始显示和结束显示时间)
    val timeline = JSONObject()
    //水印开始显示时间
    timeline["Start"] = "2"
    //水印结束显示时间
    timeline["Duration"] = "ToEND"
    watermarkConfig["Timeline"] = timeline
    return watermarkConfig
}
